﻿using Meiam.System.Interfaces;
using Meiam.System.Interfaces.IService;
using Meiam.System.Model.Entity;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Meiam.System.Model.Dto;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using SqlSugar;
using System.Text;
using System.Data;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Meiam.System.Model;
using Microsoft.Extensions.Logging;
using System.IO;
using System.Drawing;
using System.Threading;
using Google.Protobuf.WellKnownTypes;
using OfficeOpenXml.FormulaParsing.Excel.Functions.DateTime;


namespace Meiam.System.Hostd.Controllers.Gokin
{
    /// <summary>
    /// 外协挑库_销售挑库到ERP
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class CRM_WXShipOutERPController : ControllerBase
    {
        private readonly ILogger _logger;
        public readonly IWMSTokenCheckService _WMSTokenCheckService;
        public readonly string con;
        public readonly string gz_con;


        public CRM_WXShipOutERPController(ILogger<CRM_WXShipOutERPRequestDto> logger, IWMSTokenCheckService wmsTokenCheckService, IConfiguration _configuration, ILoggerFactory loggerFactory)
        {
            _WMSTokenCheckService = wmsTokenCheckService;
            con = _configuration.GetConnectionString("DDM_DbConnection_ZH");
            gz_con = _configuration.GetConnectionString("GZ_WMS_DbConnection");
            _logger = loggerFactory.CreateLogger<CRM_WXShipOutERPController>();

        }

        /// <summary>
        /// 外协挑库_销售挑库到ERP
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult PostSaleOutERP([FromBody] CRM_WXShipOutERPRequestDto strparm)
        {
            string  strMsg = "";
            object log = "";
            log = strparm;
            StringBuilder strSql = new StringBuilder();
            List<string> strSqlList = new List<string>();
            ERPGetStockOutPutResponseDto re = new ERPGetStockOutPutResponseDto();
            ERP_PickTOERPRequestDto input = new ERP_PickTOERPRequestDto();
            List<ERP_PickTOERP_DataRequestDto> details = new List<ERP_PickTOERP_DataRequestDto>();


            if (strparm.shipment_no == "")
            {
                
                strMsg = "shipment_no不能为空，运算失败！";
            }
            if (strparm.data ==null)
            {

                strMsg = "出库明细不能为空！";
            }


            Dictionary<string, string> dic = new Dictionary<string, string>(); //查询公用dic
            try
            {
                if (strMsg == "")
                {
                    int i = 1;
                    foreach (var item in strparm.data)
                    {
                        DateTime currentTime = DateTime.Now;
                        DateTime currentTime_5 = currentTime.AddMinutes(-5);

                        details.Add(new ERP_PickTOERP_DataRequestDto {
                            ORGANIZATION_CODE="H01",
                            ORDER_NUMBER= item.saleorder_no.Trim(),
                            ORDER_LINE=item.saleorderline_no.Trim(),
                            DELIVERY_DETAIL_ID= item.saleorderline_no.Trim(),
                            INVENTORY_ITEM_NUMBER=item.material_code.Trim(),
                            ORDER_UOM="块",
                            TRANSACTION_DATE= currentTime_5.ToString(),
                            LOT_NUMBER=item.source_batch.Trim(),
                            TRANSACTION_QUANTITY=item.material_amount.ToString(),
                            SUBINVENTORY_CODE=item.warehouse_code.Trim(),
                            LOCATOR_NAME=item.location_code.Trim(),
                            USER_NAME= "002021",
                            SOURCE_NUM=strparm.shipment_no.Trim(),
                            SOURCE_LINE= i.ToString(),
                            ICP_ORDER_REQ_HEADER_ID= item.saleorder_no.Trim(),
                            ICP_ORDER_REQ_LINE_NUM= item.saleorderline_no.Trim(),
                            ICP_LOGIST_REQ_HEADER_ID="",
                            ICP_LOGIST_REQ_LINE_NUM=""
                        });
                        i++;
                    }

                    if (details.Count>0)
                    {
                        input.PV_SOURCE_SYS_CODE = "WMS";
                        input.PV_BUSINESS_TYPE_CODE = "WMS_OM_PICK";
                        input.PV_SYNCHRO_FLAG = "Y";
                        input.ROWS = details;

                        Dictionary<string, string> urldic = new Dictionary<string, string>(); //URL获取dic
                        urldic.Add("function_description", "内部: ERP销售出库");//查看URL配置表地址描述
                        DataTable url_dt = MethodHelp.GetTableInfo("TMS0004", urldic, con);//获取URL地址
                        if (url_dt.Rows.Count > 0)
                        {
                            string jsonText = JsonConvert.SerializeObject(input);
                            var reAgv = DB.httpPost(url_dt.Rows[0]["interface_url"].ToString(), jsonText, "", "否");
                            ERP_PickTOERPResponseDto psp = JsonConvert.DeserializeObject<ERP_PickTOERPResponseDto>(reAgv);
                            if (psp.statusCode > 0)
                            {
                                strMsg = "ERP返回错误:" + psp.message;
                            }
                        }
                    }
                }               
            }
            catch (Exception ex)
            {
                strMsg = ex.ToString();
            }
            if (strMsg=="")
            {
                re.code = 0;
                re.message = "";
            }
            else
            {
                re.code = 500;
                re.message = strMsg;
            }

            _logger.LogInformation(JsonConvert.SerializeObject(re));
            return new JsonResult(re);
        }

      
    }
}
